<template>
  <div class="container" ref="mainCon">
    <topTitle :titleText="`应用管理`"></topTitle>
    <div class="mainCon">
      <el-row class="searchBox searchInputWidth">
        <el-form :inline="true" :model="filterField" ref="accountForm">
          <el-col :lg="8" :xl="6">
            <el-form-item label="应用名称" class="row-padding-bottom">
              <el-input
                v-model="filterField.name"
                placeholder="请输入应用名称"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="8" :xl="6">
            <el-form-item label="版本号" class="row-padding-bottom">
              <el-input
                v-model="filterField.version"
                placeholder="请输入版本号"
              />
            </el-form-item>
          </el-col>
          <el-form-item>
            <el-button
              type="primary"
              icon="icon iconfont iconchazhao1"
              @click="searchTable"
              class="searchBtn"
            >
              <span>搜索</span>
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button
              class="commonBut saveBtn funComBut"
              icon="icon iconfont icontianjia"
              @click="toAdd()"
            >
              <span class="opetareText">添加</span>
            </el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <div class="spacing"></div>
      <!-- 列表 -->
      <div
        ref="tableBox"
        :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
      >
        <el-table
          ref="tableBox1"
          :max-height="tableHeight"
          :data="tableData"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          highlight-current-row
          stripe
          v-loading="loading"
          style="border: 1px solid #dfe6ec"
        >
          <el-table-column
            align="center"
            prop="name"
            label="应用名称"
            :formatter="formatTd"
          />
          <el-table-column
            align="center"
            prop="version"
            label="版本号"
            :formatter="formatTd"
          />
          <el-table-column
            align="center"
            prop="code"
            label="应用编码"
            :formatter="formatTd"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="enabledName"
            label="状态"
            :formatter="formatTd"
          >
            <template slot-scope="scope">
              <el-switch
                class="switch"
                v-model="scope.row.enabled"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-value="ENABLED"
                inactive-value="DISABLE"
                active-text="启用"
                inactive-text="停用"
                @change="changStatus($event, scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="effectiveEndDate"
            label="版本过期时间"
            :formatter="format"
          >
            <template slot-scope="scope">
              <span v-if="scope.row.effectiveEndDate == '4712-12-31'"
                >永久有效</span
              >
              <span v-else>{{ scope.row.effectiveEndDate }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="操作"
            width="250px"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-link type="primary" @click="toInterface(scope.row)"
                >接口管理</el-link
              >
              <el-link type="primary" @click="toLog(scope.row)"
                >查看日志</el-link
              >
              <el-link type="primary" @click="toUpdate(scope.row)"
                >修改</el-link
              >
            </template>
          </el-table-column>
          <!-- 表格数据为空时，页面显示 -->
          <div slot="empty" v-show="isShow">
            <emptyTable emptyText="暂无相关信息" />
          </div>
        </el-table>
        <!-- filterField为搜索条件 -->
        <Pagination
          ref="pagination"
          @getList="getTableList"
          :filterField="filterField"
          :requestUrl="requestUrl"
          @getpageSize="getpageSize"
          @getpageNo="getpageNo"
        />
      </div>
    </div>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="appDialogVisible"
      width="40%"
      :modal-append-to-body="false"
      @close="handleClose"
    >
      <el-form
        :model="dialogFormData"
        :rules="dialogFormRules"
        ref="dialogFormData"
        label-width="150px"
        class="demo-formData"
      >
        <el-row>
          <el-form-item prop="name" label="应用名称" class="row-padding-bottom">
            <el-input
              v-model="dialogFormData.name"
              placeholder="请输入应用名称"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item
            prop="version"
            label="版本号"
            class="row-padding-bottom"
          >
            <el-input
              v-model="dialogFormData.version"
              placeholder="请输入版本号"
            />
          </el-form-item>
          <el-form-item prop="code" label="应用编码" class="row-padding-bottom">
            <el-input
              v-model="dialogFormData.code"
              placeholder="请输入单位编号"
            />
          </el-form-item>
          <el-form-item
            prop="effectiveEndDate"
            label="版本过期时间"
            class="row-padding-bottom"
          >
            <el-radio-group
              v-model="dialogFormData.effectiveEndDate"
              @change="radioChange"
              style="margin-top: 11px"
            >
              <div><el-radio label="永久有效"></el-radio></div>
              <div>
                <el-radio label="指定时间"></el-radio>
                <el-date-picker
                  v-model="effectiveEndDate"
                  v-bind:disabled="radioDisabled"
                  type="date"
                  placeholder="选择日期"
                  clearable
                  value-format="yyyy-MM-dd"
                ></el-date-picker>
              </div>
            </el-radio-group>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="btnGroup">
        <el-button @click="cancel" class="cancel">取 消</el-button>
        <el-button
          type="primary"
          class="save"
          @click.native="saveForm"
          :loading="isSaveLoading"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment'
import scrollTable from '@/mixin/scrollTable.js'
export default {
  name: 'appManageList',
  mixins: [scrollTable],
  data() {
    var validEffectiveEndDate = (rule, value, callback) => {
      if (value === '指定时间') {
        if (this.effectiveEndDate == '') {
          callback(new Error('请选择过期时间'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      requestUrl: 'api-m/inputServer/base/v1/page', //表格请求路径
      loading: false,
      isShow: false,
      tableData: [], //表格数据
      filterField: {
        name: '',
        version: '',
      },
      pageSize: 20,
      pageNo: 1,
      appOptions: [],
      appDialogVisible: false,
      dialogTitle: '',
      effectiveEndDate: '',
      isSaveLoading: false,
      edit: '',
      radioDisabled: true,
      dialogFormData: {
        id: '',
        name: '',
        code: '',
        version: '',
        enabled: 'ENABLED',
        effectiveEndDate: '',
      },
      dialogFormRules: {
        name: [
          { required: true, message: '请选择应用名称', trigger: 'change' },
        ],
        code: [
          { required: true, message: '请输入应用编码', trigger: 'change' },
          { max: 30, message: '最多可输入30个字', trigger: 'change' },
        ],
        version: [
          { required: true, message: '请选择版本号', trigger: 'change' },
        ],
        effectiveEndDate: [
          { required: true, message: '请选择版本过期时间', trigger: 'change' },
          { validator: validEffectiveEndDate, trigger: 'change' },
        ],
      },
    }
  },
  created() {
    // this.getAppList();
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
    })
  },
  methods: {
    getpageSize(val) {
      this.pageSize = val
    },
    getpageNo(val) {
      this.pageNo = val
    },

    getTableList(data) {
      this.tableData = data
      this.loading = false
      if (this.tableData.length < 1) {
        this.isShow = true
      }
    },
    //列表查询
    searchTable() {
      this.$refs.pagination.getTableListData()
    },
    format(row, column, cellValue) {
      return moment(cellValue).format('YYYY-MM-DD')
    },
    getAppList() {
      this.axios({
        method: 'post',
        url: 'api-m/inputServer/base/v1/list',
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.appOptions = response.data.result
          }
        })
        .catch((error) => {})
    },
    getSuggest(value) {
      this.axios({
        method: 'post',
        url: 'api-m/inputServer/base/v1/suggest',
        data: {
          name: value,
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            let suggest = response.data.result.split('&')
            this.dialogFormData.code = suggest[0]
            this.dialogFormData.version = suggest[1]
          }
        })
        .catch((error) => {})
    },
    handleClose() {
      this.$refs.dialogFormData.resetFields()
    },
    toAdd() {
      this.dialogTitle = '添加应用类型'
      this.edit = 'Add'
      this.dialogFormData.id = ''
      this.dialogFormData.name = ''
      this.dialogFormData.version = ''
      this.dialogFormData.code = ''
      this.dialogFormData.effectiveEndDate = ''
      this.effectiveEndDate = new Date()
      this.appDialogVisible = true
      this.$nextTick(() => {
        this.$refs.dialogFormData.resetFields()
      })
    },
    toUpdate(row) {
      this.dialogTitle = '修改应用类型'
      this.edit = 'Update'
      this.dialogFormData.id = row.id
      this.dialogFormData.name = row.name
      this.dialogFormData.version = row.version
      this.dialogFormData.code = row.code
      this.effectiveEndDate = row.effectiveEndDate
      if (row.effectiveEndDate == '4712-12-31') {
        this.dialogFormData.effectiveEndDate = '永久有效'
        this.radioDisabled = true
      } else {
        this.dialogFormData.effectiveEndDate = '指定时间'
        this.radioDisabled = false
      }
      this.appDialogVisible = true
    },
    toInterface(row) {
      this.$router.push({
        path: '/home/interfacePlatform/interfaceManageList',
        name: 'interfaceManageList',
        query: {
          id: row.id,
          version: row.version,
        },
      })
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/interfacePlatform/interfaceManageList',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    toLog(row) {
      this.$router.push({
        path: '/home/interfacePlatform/dockingLog',
        name: 'dockingLog',
        query: {
          type: 'appList',
        },
      })
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/interfacePlatform/appManageList',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    cancel() {
      this.appDialogVisible = false
    },
    saveForm() {
      this.$refs.dialogFormData.validate((valid) => {
        if (valid) {
          this.isSaveLoading = true
          this.saveFormInfo()
        } else {
          return false
        }
      })
    },
    saveFormInfo() {
      let url = 'api-m/inputServer/base/v1/add'
      if (this.edit === 'Update') {
        url = 'api-m/inputServer/base/v1/update'
      }
      if (this.dialogFormData.effectiveEndDate == '指定时间') {
        this.dialogFormData.effectiveEndDate = this.effectiveEndDate
      } else {
        this.dialogFormData.effectiveEndDate = '4712-12-31'
      }
      this.axios({
        method: 'post',
        url: url,
        data: this.dialogFormData,
      })
        .then((response) => {
          this.isSaveLoading = false
          if (!response.data.hasError) {
            this.$message({
              type: 'success',
              message: '保存成功',
            })
            this.appDialogVisible = false
            this.$refs.pagination.getTableListData()
          } else {
            this.$message({
              type: 'error',
              message: response.data.errorMsg,
            })
          }
        })
        .catch((error) => {
          this.isSaveLoading = false
        })
    },
    changStatus(event, row) {
      const vm = this
      if (event == 'DISABLE') {
        const h = this.$createElement
        this.$msgbox({
          title: '提示',
          message: h('p', null, [
            h('span', null, '设置为停用状态后，'),
            h(
              'span',
              { style: 'color: #FF4949' },
              '所有用户将无法使用该应用类型对接数据'
            ),
            h('span', '，是否确定?'),
          ]),
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              row.enabled = 'DISABLE'
              this.enable(row.id, event, done)
            } else {
              row.enabled = 'ENABLED'
              done()
            }
          },
        }).then((action) => {})
      } else {
        const h = this.$createElement
        this.$msgbox({
          title: '提示',
          message: h('p', null, [
            h('span', null, '是否确定'),
            h('span', { style: 'color: #98F203' }, '启用'),
            h('span', '该应用类型?'),
          ]),
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              row.enabled = 'ENABLED'
              this.enable(row.id, event, done)
            } else {
              row.enabled = 'DISABLE'
              done()
            }
          },
        }).then((action) => {})
      }
    },
    enable(id, enable, done) {
      this.axios({
        method: 'post',
        url: 'api-m/inputServer/base/v1/enable',
        data: {
          id: id,
          enable: enable,
        },
      })
        .then((response) => {
          done()
          if (!response.data.hasError) {
            this.$message({
              type: 'success',
              message: '保存成功',
            })
            this.$refs.pagination.getTableListData()
          } else {
            this.$message({
              type: 'error',
              message: response.data.errorMsg,
            })
          }
        })
        .catch((error) => {})
    },
    radioChange(value) {
      if (value == '指定时间') {
        this.radioDisabled = false
        this.effectiveEndDate = new Date()
      } else {
        this.radioDisabled = true
      }
    },
  },
}
</script>

<style scoped lang="less">
.container {
  .selectWidth {
    width: 100%;
  }

  .titleBox {
    border: none;
    background: #e4ebf1;
    padding: 14px 24px;
    margin-bottom: 0px;

    .listAddBtn {
      width: 136px;
      background: #009588;
      border: none;
    }

    .listAddBtn:hover {
      background: #009588;
      border-color: #009588;
      opacity: 0.8;
    }

    .blockTitle {
      font-weight: bold;
      font-size: 18px;
      color: #333;
      line-height: 40px;
    }
  }
}
/deep/ .el-tag {
  line-height: 23px;
  height: 23px;
}
/* switch按钮样式 */
/deep/.switch .el-switch__label {
  position: absolute;
  display: none;
  color: #fff !important;
}
/*打开时文字位置设置*/
/deep/.switch .el-switch__label--right {
  z-index: 1;
}
/* 调整打开时文字的显示位子 */
/deep/.switch .el-switch__label--right span {
  margin-right: 9px;
}
/*关闭时文字位置设置*/
/deep/.switch .el-switch__label--left {
  z-index: 1;
}
/* 调整关闭时文字的显示位子 */
/deep/.switch .el-switch__label--left span {
  margin-left: 9px;
}
/*显示文字*/
/deep/.switch .el-switch__label.is-active {
  display: block;
}
/* 调整按钮的宽度 */
/deep/.switch.el-switch .el-switch__core,
/deep/.el-switch .el-switch__label {
  width: 70px !important;
  margin: 0;
}
@import '../../../static/css/filterArea.less';
</style>
